package calculator;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame{	
		private Label op;
		private Label equal;
		private Label result;
		
		private TextField num1;
		private TextField num2;
		
		private Button add;
		private Button sub;
		private Button mul;
		private Button div;
		private Button equ;

			
		public Calculator() {
			this.setTitle("calculator");
			this.setBounds(100, 100, 460, 210);
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			this.setVisible(true);
			this.setLayout(null);
			
			//初始化
			num1 = new TextField("12");
			num2 = new TextField("2");
			
			op = new Label("", Label.CENTER);
			equal = new Label("=", Label.CENTER);
			result = new Label("", Label.CENTER);
			
			add = new Button("+");		
			sub = new Button("-");
			mul = new Button("*");
			div = new Button("/");
			equ = new Button("ok");
			
			//定位
			num1.setBounds(10, 10, 80, 80);
			op.setBounds(100, 10, 80, 80);
			num2.setBounds(190, 10, 80, 80);
			equal.setBounds(280, 10, 80, 80);
			result.setBounds(370, 10, 80, 80);
			
			add.setBounds(10, 100, 80, 80);
			sub.setBounds(100, 100, 80, 80);
			mul.setBounds(190, 100, 80, 80);
			div.setBounds(280, 100, 80, 80);
			equ.setBounds(370, 100, 80, 80);

			add(num1);
			add(op);
			add(num2);
			add(equal);
			add(result);
			add(add);
			add(sub);
			add(mul);
			add(div);
			add(equ);
			
			//事件监听
			ActionListener res = new ActionListener(){
				public void actionPerformed(ActionEvent e){
					result.setText("");
					int n1 = (int)Double.parseDouble(num1.getText());
					int n2 = (int)Double.parseDouble(num2.getText());
					if(op.getText().equals("+")){
						result.setText(""+(n1+n2));
					}
					if(op.getText().equals("-")){
						result.setText(""+(n1-n2));
					}
					if(op.getText().equals("*")){
						result.setText(""+(n1*n2));
					}
					if(op.getText().equals("/")){
						result.setText(""+(n1/n2));
					}
				}
			};
			
			ActionListener setop = new ActionListener(){
				public void actionPerformed(ActionEvent e){
					op.setText(((Button)e.getSource()).getLabel());
				}
			};
			
			add.addActionListener(setop);
			sub.addActionListener(setop);
			mul.addActionListener(setop);
			div.addActionListener(setop);
			
			equ.addActionListener(res);
		}
		public static void main(String[] args){
			new Calculator();
		}
}